<template>
  <view class="product-detail">
    <!-- 商品主图 -->
    <view class="single-image-wrapper" @tap="previewImage(0)">
      <image class="gallery-image" :src="product.images[0]" mode="aspectFill" />
    </view>

    <!-- 商品信息 -->
    <view class="info">
      <view class="name">{{ product.name }}</view>
      <view class="subtitle">{{ product.description }}</view>
      <view class="price-box">
        <text class="price">￥{{ selectedSpec.price || product.price }}</text>
        <text class="discount" v-if="discountPercent > 0">{{ discountPercent }}折</text>
      </view>
    </view>

    <!-- 商品规格 -->
    <view class="specs" v-for="spec in product.specs" :key="spec.name">
      <view class="spec-title">{{ spec.name }}</view>
      <view class="spec-options">
        <view
          class="spec-option"
          :class="{ selected: selectedSpecs[spec.name] === option.value, disabled: !option.available }"
          v-for="option in spec.options"
          :key="option.value"
          @tap="selectSpec(spec.name, option)"
        >
          {{ option.label }}
        </view>
      </view>
    </view>

    <!-- 数量选择 -->
    <view class="quantity-box">
      <view class="quantity-title">数量</view>
      <view class="quantity-control">
        <button @tap="updateQuantity(-1)" size="mini">-</button>
        <text class="quantity">{{ quantity }}</text>
        <button @tap="updateQuantity(1)" size="mini">+</button>
      </view>
    </view>

    <!-- 操作栏 -->
    <view class="bottom-bar">
      <view class="favorite" @tap="toggleFavorite">
        <image :src="isFavorited ? '/static/heart-fill.png' : '/static/heart.png'" class="icon" />
        <text>{{ isFavorited ? '已收藏' : '收藏' }}</text>
      </view>
      <view class="action-button cart" @tap="addToCart">加入购物车</view>
      <view class="action-button buy" @tap="buyNow">立即购买</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      BASE_URL: '', // ✅ 修改：放到 data 里初始化
      productId: null,
      product: {
        id: null,
        images: [],
        detailImages: [],
        specs: [],
        name: '',
        subtitle: '',
        price: 0,
        originalPrice: 0,
        stock: 0,
        description: '',
        tags: [],
        sales: 0,
        rating: 0
      },
      selectedSpecs: {},
      quantity: 1,
      maxQuantity: 999,
      isFavorited: false
    }
  },

  computed: {
    selectedSpec() {
      const specName = '规格'
      const selectedValue = this.selectedSpecs[specName]
      if (selectedValue) {
        const specType = this.product.specs.find(s => s.name === specName)
        if (specType) {
          return specType.options.find(o => o.value === selectedValue) || {}
        }
      }
      return {}
    },
    discountPercent() {
      const current = this.selectedSpec.price || this.product.price
      const original = this.selectedSpec.originalPrice || this.product.originalPrice
      if (original > current) {
        return Math.round((current / original) * 10)
      }
      return 0
    }
  },

  onLoad(options) {
    this.BASE_URL = getApp().$vm.$global.baseURL // ✅ 修改：避免模板提前引用为空
    if (options.id) {
      this.productId = parseInt(options.id)
      this.loadProductDetail()
      this.loadProductSpecs()
      this.checkIfFavorited()
    }
  },

  methods: {
    fullImageUrl(img) {
      if (!img) return ''
      return img.startsWith('http') ? img : this.BASE_URL + img
    },

    loadProductDetail() {
      uni.request({
        url: `${this.BASE_URL}/api/good/${this.productId}`,
        success: (res) => {
          if (res.data.code === '200' && res.data.data) {
            const data = res.data.data
            this.product = {
              ...this.product,
              id: data.id,
              name: data.name,
              description: data.description,
              price: data.saleMoney,
              originalPrice: data.saleMoney / (data.discount || 1),
              stock: data.store || 999,
              sales: data.sales || 0,
              rating: 4.9,
              images: data.imgs ? [this.fullImageUrl(data.imgs)] : [],
              detailImages: data.imgs ? [this.fullImageUrl(data.imgs)] : []
            }
          }
        },
        fail: () => {
          uni.showToast({ title: '加载商品失败', icon: 'none' })
        }
      })
    },

    loadProductSpecs() {
      uni.request({
        url: `${this.BASE_URL}/api/good/standard/${this.productId}`,
        success: (res) => {
          if (res.data.code === '200' && res.data.data) {
            const specList = JSON.parse(res.data.data)
            this.product.specs = [
              {
                name: '规格',
                options: specList.map(item => ({
                  label: item.value,
                  value: item.value,
                  available: item.store > 0,
                  price: item.price,
                  originalPrice: item.price / 0.9,
                  stock: item.store
                }))
              }
            ]
            this.initDefaultSpecs()
          }
        },
        fail: () => {
          uni.showToast({ title: '加载规格失败', icon: 'none' })
        }
      })
    },

    initDefaultSpecs() {
      this.product.specs.forEach(specType => {
        const availableOption = specType.options.find(option => option.available)
        if (availableOption) {
          this.selectedSpecs[specType.name] = availableOption.value
          this.maxQuantity = availableOption.stock
        }
      })
    },

    previewImage(index) {
      if (this.product.images.length === 0) return
      uni.previewImage({
        current: this.product.images[index],
        urls: this.product.images
      })
    },

    selectSpec(specName, option) {
      if (!option.available) {
        uni.showToast({ title: '该规格暂时缺货', icon: 'none' })
        return
      }
      this.selectedSpecs[specName] = option.value
      this.maxQuantity = option.stock || 999
      if (this.quantity > this.maxQuantity) {
        this.quantity = this.maxQuantity
      }
    },

    updateQuantity(change) {
      const newQty = this.quantity + change
      if (newQty >= 1 && newQty <= this.maxQuantity) {
        this.quantity = newQty
      } else if (newQty < 1) {
        uni.showToast({ title: '商品数量不能少于1', icon: 'none' })
      } else {
        uni.showToast({ title: `库存不足，最多可买${this.maxQuantity}`, icon: 'none' })
      }
    },

    addToCart() {
      const selected = this.selectedSpecs['规格']
      if (!selected) {
        uni.showToast({ title: '请选择规格', icon: 'none' })
        return
      }

      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo || !userInfo.id) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' })
        }, 1000)
        return
      }

      const cartItem = {
        userId: userInfo.id,
        goodId: this.product.id,
        count: this.quantity,
        standard: selected
      }

      console.log('📦 添加购物车请求数据:', cartItem)

      uni.request({
        url: `${this.BASE_URL}/api/cart`,
        method: 'POST',
        data: cartItem,
        header: {
          'Content-Type': 'application/json',
          'Authorization': userInfo.token || '' // ✅ 修改：如果后端需要 token
        },
        success: (res) => {
          console.log('🛒 响应结果：', res)
          if (res.data && res.data.code === '200') {
            uni.showToast({ title: '加入成功', icon: 'success' })
          } else {
            uni.showToast({ title: res.data?.msg || '添加失败', icon: 'none' })
          }
        },
        fail: (err) => {
          console.error('❌ 添加购物车失败：', err)
          uni.showToast({ title: '网络错误', icon: 'none' })
        }
      })
    },

    buyNow() {
      uni.showLoading({ title: '正在支付...' })
      
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
      
          setTimeout(() => {
            // 跳转到首页
            uni.switchTab({ url: '/pages/index/index' })
          }, 1600)
        }, 2000)
    },

    toggleFavorite() {
      this.isFavorited = !this.isFavorited
      let favorites = uni.getStorageSync('favorites') || []
      if (this.isFavorited) {
        favorites.push(this.productId)
      } else {
        favorites = favorites.filter(id => id !== this.productId)
      }
      uni.setStorageSync('favorites', favorites)
      uni.showToast({ title: this.isFavorited ? '已收藏' : '取消收藏', icon: 'none' })
    },

    checkIfFavorited() {
      const favorites = uni.getStorageSync('favorites') || []
      this.isFavorited = favorites.includes(this.productId)
    }
  }
}
</script>


<style scoped>
.product-detail {
  padding-bottom: 120rpx; /* 留出底部操作栏空间 */
}
.single-image-wrapper {
  height: 750rpx;
  background-color: #fff;
}
.gallery-image {
  width: 100%;
  height: 100%;
}
.info {
  margin-top: 20rpx;
}
.name {
  font-size: 36rpx;
  font-weight: bold;
}
.subtitle {
  font-size: 26rpx;
  color: #999;
  margin-top: 10rpx;
}
.price-box {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}
.price {
  font-size: 40rpx;
  color: red;
}
.original-price {
  font-size: 28rpx;
  color: #ccc;
  text-decoration: line-through;
  margin-left: 20rpx;
}
.discount {
  font-size: 24rpx;
  color: #f60;
  margin-left: 20rpx;
}
.specs {
  margin-top: 30rpx;
}
.spec-title {
  font-weight: bold;
  margin-bottom: 10rpx;
}
.spec-options {
  display: flex;
  flex-wrap: wrap;
}
.spec-option {
  padding: 10rpx 20rpx;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
  border: 1px solid #ccc;
}
.spec-option.selected {
  background-color: #388f4a;
  color: #fff;
  border-color: #388f4a;
}
.spec-option.disabled {
  color: #ccc;
  border-color: #eee;
}
.quantity-box {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.quantity-title {
  font-size: 30rpx;
}
.quantity-control {
  display: flex;
  align-items: center;
}
.quantity {
  margin: 0 20rpx;
  font-size: 28rpx;
}
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  border-top: 1px solid #eee;
  background: #fff;
  z-index: 10;
}
.favorite {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 24rpx;
}
.favorite .icon {
  width: 40rpx;
  height: 40rpx;
  display: block;
  margin: 0 auto 8rpx;
}
.action-button {
  flex: 2;
  text-align: center;
  padding: 40rpx 0;
  color: #fff;
  font-size: 28rpx;
}
.action-button.cart {
  background: #ff9900;
}
.action-button.buy {
  background: #e64340;
}
</style>
